const mongoose = require('../connect')

const CategoryCounterSchema = mongoose.Schema({
    _id: { type: String },
    seq: { type: Number, default: 0 }
  })
  
const CategoryCounter = mongoose.model('CategoryCounter', CategoryCounterSchema)
  
const CategorySchema = mongoose.Schema({
  label: String,
  desc: String,
  meta: {
      createAt: {
          type: Date,
          default: Date.now()
      },
      updateAt: {
          type: Date,
          default: Date.now()
      }
  }
})

CategorySchema.pre('save', function (next) {
    let doc = this;
    CategoryCounter.findByIdAndUpdate({ _id: 'categoryId' }, { $inc: { seq: 1 } }, { new: true, upsert: true }, function (error, counter) {
        if (error)
            return next(error);
        doc._id = counter.seq;
        console.log(counter.seq)
        if (doc.isNew){
          doc.meta.createdAt = doc.meta.updatedAt = Date.now()
        }else {
          doc.meta.updatedAt = Date.now()
        }
        next()
    });
  })

const Category = mongoose.model('Category', CategorySchema)

module.exports = Category
